package respository

import (
	"gitee.com/song-yao-shun/MQH/common"
	"gitee.com/song-yao-shun/MQH/dto"
	"gitee.com/song-yao-shun/MQH/model"
	"gitee.com/song-yao-shun/MQH/vo"
	"gorm.io/gorm"
	"log"
)

//定义接口和定义增删改查的方法
type IPageRepository interface {
	Create(page model.Page)
	Update(page model.Page)
	SelectById(Id int)
	SelectFullPageById(Id int)
	DeleteById(Id int)
	List(list vo.PageList)
}

type PageRepository struct {
	DB *gorm.DB
}

func (p PageRepository) Create(page model.Page) (int, error){

	if err := p.DB.Create(&page).Error; err != nil {
		log.Printf("新增失败，错误信息为：%v",err)
		return 0, err
	}

	return page.ID, nil
}

func (p PageRepository) Update(page model.Page) (*model.Page, error){

	if err := p.DB.Updates(&page).Error;err != nil {
		return nil, err
	}

	return &page,nil
}

func (p PageRepository) SelectById(Id int) (page *model.Page, err error){

	if res := p.DB.First(&page, Id);res.Error != nil{
		return nil, res.Error
	}

	return
}

func (p PageRepository) SelectFullPageById(Id int) *dto.FullPageDto{

	p.DB = p.DB.Where("pages.id = ?", Id)
	selectSql := "pages.id,pages.name,pages.application_id as app_id," +
		"applications.name as app_name,pages.img,pages.type,pages.desc"
	joinsSql := "left join applications on pages.application_id = applications.id"

	var fullPage  dto.FullPageDto
	p.DB.Model(&model.Page{}).Select(selectSql).Joins(joinsSql).Scan(&fullPage)

	return &fullPage
}

func (p PageRepository) DeleteById(Id int) (rowsAffected int64) {

	rowsAffected = p.DB.Where("id = ?", Id).Delete(model.Page{}).RowsAffected
	if rowsAffected != 1 {
		log.Printf("数据删除失败，删除操作影响行数为：%v，删除的id为：%v",rowsAffected,Id)
	}

	return
}

func (p PageRepository) List(list vo.PageList) (fullPages []dto.FullPageDto, total int64){
	// 条件查询
	if list.ApplicationId > 0  {
		p.DB = p.DB.Where("pages.application_id = ?", list.ApplicationId)
	}
	if list.ID > 0  {
		p.DB = p.DB.Where("pages.id = ?", list.ID)
	}
	if list.Name != ""  {
		p.DB = p.DB.Where("pages.name like ?", "%" + list.Name + "%")
	}
	if list.Type != ""  {
		p.DB = p.DB.Where("pages.type = ?", list.Type)
	}
	if list.PageNum == 0  {
		list.PageNum = 1
	}
	if list.PageSize == 0  {
		list.PageSize = 10
	}
	selectSql := "pages.id,pages.name,pages.application_id as app_id," +
		"applications.name as app_name,pages.img,pages.type,pages.desc"
	joinsSql := "left join applications on pages.application_id = applications.id"
	//总记录数
	p.DB.Model(&model.Page{}).Count(&total)

	p.DB.Model(&model.Page{}).Select(selectSql).Joins(joinsSql).Order("pages.created_at desc").
		Offset((list.PageNum -1) * list.PageSize).Limit(list.PageSize).Scan(&fullPages)

	return
}

func NewPageRepository() PageRepository{
	db := common.GetDB()
	//db.AutoMigrate(model.Page{})

	return PageRepository{DB: db}
}